using System;
using System.Windows.Forms;

namespace MatrixOperationsWinForms
{
    public class Matrix
    {
        // 矩阵乘法：返回矩阵A和矩阵B的乘积
        public static double[,] Multiply(double[,] A, double[,] B)
        {
            int rowsA = A.GetLength(0);
            int colsA = A.GetLength(1);
            int rowsB = B.GetLength(0);
            int colsB = B.GetLength(1);

            if (colsA != rowsB)
                throw new InvalidOperationException("矩阵维度不匹配，无法相乘");

            double[,] result = new double[rowsA, colsB];

            for (int i = 0; i < rowsA; i++)
            {
                for (int j = 0; j < colsB; j++)
                {
                    for (int k = 0; k < colsA; k++)
                    {
                        result[i, j] += A[i, k] * B[k, j];
                    }
                }
            }

            return result;

        }
        public static double[,] Multiply(double[,] A, double[,] B, double[,] C)
        {
            // 首先计算 A * B
            double[,] tempResult = Multiply(A, B);
            // 然后计算 (A * B) * C
            return Multiply(tempResult, C);
        }


        // 矩阵求逆：使用高斯-约尔当消去法
        public static double[,] Inverse(double[,] matrix)
        {
            int n = matrix.GetLength(0);

            if (n != matrix.GetLength(1))
                throw new InvalidOperationException("只有方阵可以求逆");

            // 初始化单位矩阵
            double[,] result = new double[n, n];
            for (int i = 0; i < n; i++)
                result[i, i] = 1;

            // 进行高斯-约尔当消去法
            for (int i = 0; i < n; i++)
            {
                // 寻找主元
                if (matrix[i, i] == 0)
                {
                    for (int j = i + 1; j < n; j++)
                    {
                        if (matrix[j, i] != 0)
                        {
                            SwapRows(matrix, i, j);
                            SwapRows(result, i, j);
                            break;
                        }
                    }
                }

                // 归一化当前行
                double diag = matrix[i, i];
                for (int j = 0; j < n; j++)
                {
                    matrix[i, j] /= diag;
                    result[i, j] /= diag;
                }

                // 消去其他行
                for (int j = 0; j < n; j++)
                {
                    if (i != j)
                    {
                        double factor = matrix[j, i];
                        for (int k = 0; k < n; k++)
                        {
                            matrix[j, k] -= factor * matrix[i, k];
                            result[j, k] -= factor * result[i, k];
                        }
                    }
                }
            }

            return result;
        }

        // 辅助函数：交换矩阵的两行
        private static void SwapRows(double[,] matrix, int row1, int row2)
        {
            int n = matrix.GetLength(1);
            for (int i = 0; i < n; i++)
            {
                double temp = matrix[row1, i];
                matrix[row1, i] = matrix[row2, i];
                matrix[row2, i] = temp;
            }
        }
    }
    partial class MatrixForm
    {
        private System.ComponentModel.IContainer components = null;
        private System.Windows.Forms.TextBox txtMatrixA;
        private System.Windows.Forms.TextBox txtMatrixB;
        private System.Windows.Forms.TextBox txtMatrixC; // 新增的文本框
        private System.Windows.Forms.TextBox txtResult;
        private System.Windows.Forms.Button btnMultiplyThree; // 新增的按钮
        private System.Windows.Forms.Button btnMultiply;
        private System.Windows.Forms.Button btnInverse;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.txtMatrixA = new System.Windows.Forms.TextBox();
            this.txtMatrixB = new System.Windows.Forms.TextBox();
            this.txtMatrixC = new System.Windows.Forms.TextBox();
            this.txtResult = new System.Windows.Forms.TextBox();
            this.btnMultiplyThree = new System.Windows.Forms.Button();
            this.btnMultiply = new System.Windows.Forms.Button();
            this.btnInverse = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();


            this.SuspendLayout();
            // 
            // txtMatrixA
            // 
            this.txtMatrixA.Location = new System.Drawing.Point(12, 30);
            this.txtMatrixA.Multiline = true;
            this.txtMatrixA.Name = "txtMatrixA";
            this.txtMatrixA.Size = new System.Drawing.Size(300, 100);
            this.txtMatrixA.TabIndex = 0;
            // 
            // txtMatrixB
            // 
            this.txtMatrixB.Location = new System.Drawing.Point(12, 160);
            this.txtMatrixB.Multiline = true;
            this.txtMatrixB.Name = "txtMatrixB";
            this.txtMatrixB.Size = new System.Drawing.Size(300, 100);
            this.txtMatrixB.TabIndex = 1;
            // txtMatrixC
            this.txtMatrixC = new System.Windows.Forms.TextBox();
            this.txtMatrixC.Location = new System.Drawing.Point(12, 290); // 设置位置
            this.txtMatrixC.Multiline = true;
            this.txtMatrixC.Name = "txtMatrixC";
            this.txtMatrixC.Size = new System.Drawing.Size(300, 100);
            this.txtMatrixC.TabIndex = 7;
            // 
            // txtResult
            // 
            this.txtResult.Location = new System.Drawing.Point(12, 420);
            this.txtResult.Multiline = true;
            this.txtResult.Name = "txtResult";
            this.txtResult.ReadOnly = true;
            this.txtResult.Size = new System.Drawing.Size(300, 100);
            this.txtResult.TabIndex = 2;
            // 
            // btnMultiply
            // 
            this.btnMultiply.Location = new System.Drawing.Point(350, 50);
            this.btnMultiply.Name = "btnMultiply";
            this.btnMultiply.Size = new System.Drawing.Size(100, 50);
            this.btnMultiply.TabIndex = 3;
            this.btnMultiply.Text = "二矩阵乘法";
            this.btnMultiply.UseVisualStyleBackColor = true;
            this.btnMultiply.Click += new System.EventHandler(this.btnMultiply_Click);
            // 
            // btnInverse
            // 
            this.btnInverse.Location = new System.Drawing.Point(350, 180);
            this.btnInverse.Name = "btnInverse";
            this.btnInverse.Size = new System.Drawing.Size(100, 50);
            this.btnInverse.TabIndex = 4;
            this.btnInverse.Text = "矩阵求逆";
            this.btnInverse.UseVisualStyleBackColor = true;
            this.btnInverse.Click += new System.EventHandler(this.btnInverse_Click);
            // btnMultiplyThree
            this.btnMultiplyThree = new System.Windows.Forms.Button();
            this.btnMultiplyThree.Location = new System.Drawing.Point(350, 300); // 设置位置
            this.btnMultiplyThree.Name = "btnMultiplyThree";
            this.btnMultiplyThree.Size = new System.Drawing.Size(100, 50);
            this.btnMultiplyThree.TabIndex = 8;
            this.btnMultiplyThree.Text = "三矩阵乘法";
            this.btnMultiplyThree.UseVisualStyleBackColor = true;
            this.btnMultiplyThree.Click += new System.EventHandler(this.btnMultiplyThree_Click);

            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 10);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 12);
            this.label1.TabIndex = 5;
            this.label1.Text = "矩阵A输入:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 140);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(65, 12);
            this.label2.TabIndex = 6;
            this.label2.Text = "矩阵B输入:";
            //label3
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(12, 270);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(65, 12);
            this.label3.TabIndex = 6;
            this.label3.Text = "矩阵C输入:";
            //label4
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(12, 400);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(65, 12);
            this.label4.TabIndex = 6;
            this.label4.Text = "结果输出:";
            // 
            // MatrixForm
            // 
            this.ClientSize = new System.Drawing.Size(484, 600);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.btnInverse);
            this.Controls.Add(this.btnMultiply);
            this.Controls.Add(this.txtResult);
            this.Controls.Add(this.txtMatrixB);
            this.Controls.Add(this.txtMatrixA);
            this.Controls.Add(this.txtMatrixC);
            this.Controls.Add(this.btnMultiplyThree);
            this.Name = "MatrixForm";
            this.Text = "矩阵运算";
            this.ResumeLayout(false);
            this.PerformLayout();
        }
    }
    public partial class MatrixForm : Form
    {
        public MatrixForm()
        {
            InitializeComponent();
        }

        // 点击矩阵乘法按钮时执行
        private void btnMultiply_Click(object sender, EventArgs e)
        {
            try
            {
                double[,] A = ParseMatrix(txtMatrixA.Text);
                double[,] B = ParseMatrix(txtMatrixB.Text);

                double[,] result = Matrix.Multiply(A, B);

                txtResult.Text = MatrixToString(result);
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误: " + ex.Message);
            }
        }
        private void btnMultiplyThree_Click(object sender, EventArgs e)
        {
            try
            {
                double[,] A = ParseMatrix(txtMatrixA.Text);
                double[,] B = ParseMatrix(txtMatrixB.Text);
                double[,] C = ParseMatrix(txtMatrixC.Text);

                double[,] result = Matrix.Multiply(A, B, C);

                txtResult.Text = MatrixToString(result);
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误: " + ex.Message);
            }
        }

        // 点击矩阵求逆按钮时执行
        private void btnInverse_Click(object sender, EventArgs e)
        {
            try
            {
                double[,] A = ParseMatrix(txtMatrixA.Text);

                double[,] result = Matrix.Inverse(A);

                txtResult.Text = MatrixToString(result);
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误: " + ex.Message);
            }
        }

        // 将字符串解析为矩阵
        private double[,] ParseMatrix(string input)
        {
            string[] rows = input.Trim().Split('\n');
            int rowCount = rows.Length;
            int colCount = rows[0].Trim().Split(' ').Length;

            double[,] matrix = new double[rowCount, colCount];

            for (int i = 0; i < rowCount; i++)
            {
                string[] values = rows[i].Trim().Split(' ');
                for (int j = 0; j < colCount; j++)
                {
                    // 处理分数输入
                    string value = values[j].Trim();
                    if (value.Contains('/'))
                    {
                        string[] fractionParts = value.Split('/');
                        double numerator = double.Parse(fractionParts[0]);
                        double denominator = double.Parse(fractionParts[1]);
                        matrix[i, j] = numerator / denominator; // 转换为小数
                    }
                    else
                    {
                        matrix[i, j] = double.Parse(value); // 处理整数或小数
                    }
                }
            }

            return matrix;
        }


        // 将矩阵转换为字符串输出
        private string MatrixToString(double[,] matrix)
        {
            int rows = matrix.GetLength(0);
            int cols = matrix.GetLength(1);
            string result = "";

            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    result += matrix[i, j].ToString("F2") + " ";
                }
                result += Environment.NewLine;
            }

            return result;
        }
    }
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MatrixForm());
        }
    }
}